package co.yixiang.yshop.module.system.controller.admin.captcha;

import cn.hutool.core.util.StrUtil;
import co.yixiang.yshop.framework.common.pojo.CommonResult;
import co.yixiang.yshop.framework.common.util.servlet.ServletUtils;
import co.yixiang.yshop.module.system.controller.admin.captcha.vo.ImageCaptchaGetReqVO;
import co.yixiang.yshop.module.system.controller.admin.captcha.vo.ImageCaptchaGetRespVO;
import co.yixiang.yshop.module.system.controller.admin.captcha.vo.ImageCaptchaVerifyReqVO;
import co.yixiang.yshop.module.system.controller.admin.captcha.vo.ImageCaptchaVerifyRespVO;
import co.yixiang.yshop.module.system.service.captcha.ImageCaptchaService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import jakarta.annotation.Resource;
import jakarta.annotation.security.PermitAll;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
 
import org.springframework.http.ResponseEntity;

/**
 * 图片选择验证码控制器
 *
 * @author yshop
 */
@Tag(name = "管理后台 - 图片选择验证码")
@RestController("adminImageCaptchaController")
@RequestMapping("/system/captcha/image")
@Slf4j
public class ImageCaptchaController {

    @Resource
    private ImageCaptchaService imageCaptchaService;

    @PostMapping("/get")
    @Operation(summary = "获取图片选择验证码")
    @PermitAll
    public CommonResult<ImageCaptchaGetRespVO> getImageCaptcha(@RequestBody @Valid ImageCaptchaGetReqVO reqVO,
                                                               HttpServletRequest request) {
        String browserInfo = getRemoteId(request);
        ImageCaptchaGetRespVO result = imageCaptchaService.getImageCaptcha(reqVO, browserInfo);
        log.info("生成图片验证码: token={}, targetCategory={}, imagesCount={}",
                result.getToken(), result.getTargetCategory(), result.getImages().size());
        System.out.println(result.getImages().get(0));
        return CommonResult.success(result);
    }

    @PostMapping("/verify")
    @Operation(summary = "验证图片选择验证码")
    @PermitAll
    public CommonResult<ImageCaptchaVerifyRespVO> verifyImageCaptcha(@RequestBody @Valid ImageCaptchaVerifyReqVO reqVO,
                                                                     HttpServletRequest request) {
        String browserInfo = getRemoteId(request);
        return CommonResult.success(imageCaptchaService.verifyImageCaptcha(reqVO, browserInfo));
    }

    // 兼容旧的文件系统读取接口，保留但不再使用（已改为 DB 存储 URL）
    @GetMapping("/image/{category}/{filename}")
    @Operation(summary = "获取验证码图片(Deprecated)")
    @PermitAll
    public ResponseEntity<Void> getCaptchaImage(@PathVariable String category, 
                                                @PathVariable String filename,
                                                HttpServletResponse response) {
        return ResponseEntity.notFound().build();
    }

    private static String getRemoteId(HttpServletRequest request) {
        String ip = ServletUtils.getClientIP(request);
        String ua = request.getHeader("user-agent");
        if (StrUtil.isNotBlank(ip)) {
            return ip + ua;
        }
        return request.getRemoteAddr() + ua;
    }
}
